
#include <cassert>

#include <anb/common/utils.h>

#include "loop.h"
#include "utils.h"

namespace anb { namespace net {

loop::loop(const std::string& name) : uvo(name, uvo::type::uvo_loop) {
    m_loop = uv_loop_new();
}

loop::~loop() {
	stop();
}

const std::string loop::DEFAULT_LOOP_NAME = "loop";

int loop::start() {
    return uv_run(m_loop, UV_RUN_DEFAULT);
}

void loop::stop() {
	if (m_loop) {
		uv_stop(m_loop);
		m_loop = NULL;
	}
}

uv_tcp_t* loop::create_tcp() {
	uv_tcp_t* tcp = (uv_tcp_t*)anb::common::utils::malloc(sizeof(uv_tcp_t));
	int err = uv_tcp_init(m_loop, tcp);
	if (err) {
		log_error(err, "uv_tcp_init error");
		anb::common::utils::free(tcp);
		assert(false);
		return NULL;
	}
	return tcp;
}

void loop::close(uv_handle_t* handle) {
	uv_close(handle, _closed);
}

void loop::close(uv_tcp_t* tcp) {
	uv_read_stop((uv_stream_t*)tcp);
	uv_close((uv_handle_t*)tcp, _closed);
}

void loop::_closed(uv_handle_t* handle) {
	anb::common::utils::free(handle);
}

void loop::async() {
	uv_async_t async;
	async.data = "";
	//uv_async_init(m_loop, &async, xxxx);
}

} }